#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

class client
{
public:
    client(const char* ip, uint16_t port)
    :_server_ip(ip), _server_port(port), _sock_fd(-1)
    {}

    void client_init()
    {
        //create socket
        _sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock_fd < 0)
        {
            std::cerr << "create socket error" << errno << strerror(errno) <<std::endl;
            exit(0);
        }

        std::cout << "create socket success" << std::endl;


        //客户端不需要绑定，系统会默认处理

    }

    void client_start()
    {
        bool quit = false;
        std::string message;
        socklen_t len = sizeof(_to_server);
        _to_server.sin_addr.s_addr = inet_addr(_server_ip.c_str());
        _to_server.sin_port = htons(_server_port);
        while (!quit)
        {
            std::cout << "please enter you message: ";
            std::cin >> message ;
            std::cout << std::endl;
            //std::cout <<"if you want to continue? please enter 0 for continue" <<std::endl;
            //std::cin >> quit;
            sendto(_sock_fd, message.c_str(), message.size(), 0,
                    (struct sockaddr*)&_to_server, len);
            
        }

    }

private:
    std::string _server_ip;
    uint16_t _server_port;
    int _sock_fd;
    struct sockaddr_in _to_server;
};